/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.yuhanginfo.common.utils.ReadProperties;
import com.yuhanginfo.common.web.BaseController;

/**
 * 文件管理
 * @author yinhao
 * @version 2017-09-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/file/")
public class FileController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	private static final String SCRIPT = "<script type=\"text/javascript\">";
	private static final String CALLFUNCTION = "window.parent.CKEDITOR.tools.callFunction(";
	private static final String SCRIPTEND = "</script>";
	
	private void getFile(String filePath, HttpServletResponse response) {
		File file = new File(filePath);
		try(BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream());
				FileInputStream fis = new FileInputStream(file);){
		    if(!file.exists()){
		    	return;
		    }
		    byte[] b = new byte[1024*1024];
		    int length = -1;
		    while((length = fis.read(b, 0, b.length)) != -1){
		    	bos.write(b, 0, length);
		    }
		} catch (Exception ex) {
			logger.info("getFile",ex);
		}
	}
	
	@RequestMapping(value = "getImg")
	public void getImg(String filePath, HttpServletResponse response) {
		String imgPath = ReadProperties.readByName("image_save_path");
		if(filePath.indexOf(imgPath) != 0){
			return;
		}
		this.getFile(filePath, response);
	}
	
	@RequestMapping(value = "uploadImage")
	public void uploadImage(@RequestParam("upload") MultipartFile file,//  
			HttpServletRequest request, //  
			HttpServletResponse response) throws IOException {
		//上传到本地  
		String directoryName = ReadProperties.readByName("image_save_path");
		String callback = request.getParameter("CKEditorFuncNum");
        PrintWriter out = response.getWriter();
		 // 图片名称
        Date d = new Date();
		Random r = new Random();
        String fileName = String.valueOf(d.getTime()+r.nextInt(10000));
        String uploadContentType = file.getContentType();  
        String cKEditorFuncNum = request.getParameter("CKEditorFuncNum"); 
        if ("image/pjpeg".equals(uploadContentType)  
    		|| "image/jpeg".equals(uploadContentType)) {  
    		// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg  
        	fileName = fileName + ".jpg";  
    		} else if ("image/png".equals(uploadContentType)
    		|| "image/x-png".equals(uploadContentType)) {  
    		// IE6上传的png图片的headimageContentType是"image/x-png"  
    			fileName = fileName + ".png"; 
    		} else if ("image/gif".equals(uploadContentType)) {  
    			fileName = fileName + ".gif"; 
    		} else if ("image/bmp".equals(uploadContentType)) { 
    			fileName = fileName + ".bmp";  
    		} else {  
    		out.println(SCRIPT);  
    		out.println(CALLFUNCTION  
    		+ cKEditorFuncNum + ",'',"  
    		+ "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");  
    		out.println(SCRIPTEND);  
    		return;  
    		}  
    		if (file.getSize() > 1024 * 1024 * 2) {  
    		out.println(SCRIPT);  
    		out.println(CALLFUNCTION  
    		+ cKEditorFuncNum + ",''," + "'文件大小不得大于2M');");  
    		out.println(SCRIPTEND);  
    		return;  
		}
        // 如果路径不存在，则创建该路径
        File realPathDirectory = new File(directoryName);
        if (!realPathDirectory.exists()) {
            realPathDirectory.mkdirs();
        }
        // 重命名上传后的文件名 111112323.jpg
        
        // 定义上传路径 .../upload/111112323.jpg
        File uploadFile = new File(realPathDirectory + "/" + fileName);
        file.transferTo(uploadFile);
        // 结合ckeditor功能
        // imageContextPath为图片在服务器地址，如upload/123.jpg,非绝对路径
        String imageContextPath = directoryName + fileName;
        out.println(SCRIPT);
        out.println(CALLFUNCTION + callback + ",'" + imageContextPath + "',''" + ")");
        out.println(SCRIPTEND);
        out.flush();
        out.close();
	}
}